import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:ls_work/a_elder/models/code_value_entity.dart';
import 'package:ls_work/config/global_configs.dart';
import 'package:ls_work/message/message_config.dart';
import 'package:ls_work/model/patrol/patrol_task_model.dart';
import 'package:ls_work/net/post_request.dart';
import 'package:ls_work/net/response/patrol/patrol_check_dats.dart';
import 'package:ls_work/util/ext_utils.dart';
import 'package:ls_work/util/utils.dart';
import 'package:ls_work/viewmodel/model/combo_data_model.dart';
import 'package:nfc_manager/nfc_manager.dart';

import '../../ui/patrol/patrol_detail_page.dart';

class PatrolListHomeViewModel extends BaseViewModel {
  TickerProvider? vs;
  TabController? controller;
  PatrolListHomeViewModel(BuildContext context, {this.vs}) : super(context) {
    if(vs!=null){
      controller = TabController(length: taskList.length, vsync: vs!);
    }
  }

  PatrolCheckDats? patrolData;
  var patrolModel = PatrolTaskModel();
  List<GuardTaskExecuteBeanList> taskList = [];

  // TabController controller;

  var dateTimeFormat = ["yyyy",'-','mm','-','dd',' ','HH',':','mm',':','ss'];

  var model = ComboDataModel();
  var areaList = <CodeValue>[];
  CodeValue selectedArea = CodeValue(nameCn: "全部");

  Future<void> getPatrolAreaList() async {
    try{
      var list =  await model.getComboData("1000");
      list.insert(0, CodeValue(nameCn: "全部"));
      areaList = list;
    }catch(e){

    }
  }

  Future<void> getPatrolData() async {
    showLoadingState();
    try {
      var data = await PostRequest.patrolList("全部"==selectedArea?.name?"":selectedArea?.name??"");
      if ("0" == data['code']) {
        patrolData = PatrolCheckDats.fromJson(data['data']);
        var list = patrolData?.guardTaskExecuteBeanList??[];
        list.sort((o1,o2){
          return o2.startDate!.compareTo(o1.startDate!);
        });
         if(GlobalConfigs.filterPatrolTask){
           var now = DateTime.now();
           taskList = list.takeWhere<GuardTaskExecuteBeanList>((item){
             return now.isAfter(item.startDate!.toDate()!);
           });
         }else{
           taskList = list;
         }
        if(vs!=null){
          controller = TabController(length: taskList.length, vsync: vs!,initialIndex: controller!.index);
        }
         // controller.animateTo(value)

        showContent();
        notifyListeners();
      } else {
        showErrorState(data['msg']);
      }
    } catch (e) {
      showErrorState(NetErrorUtils.getNetError(e));
    }
  }

  Future<void> scanCode() async {
    var code = await Utils.scan();
    if (!code.isNullOrEmpty()) {
      // var index = controller.index;
      // var id = taskList[index].id;
      Go().push(PatrolDetailPage(code,));


    }
  }

  Future<void> startNfc() async {
    var nfcEnable = await NfcManager.instance.isAvailable();
    if (nfcEnable) {
      NfcManager.instance.startSession(
          onDiscovered: (NfcTag tag) async {
            Ndef? ndef = Ndef.from(tag);
            if (ndef?.cachedMessage?.records.isNotEmpty ?? false) {
              var payload = ndef?.cachedMessage?.records[0].payload;
              // var languageLength = payload[0];
              // showToast(languageLength.toString());
              var str = String.fromCharCodes(
                payload!,
                3,
              );
              if(taskList.isEmpty){
                NfcManager.instance.stopSession();
                return;
              }
              if (!str.isNullOrEmpty()) {
                // var index = controller.index;
                // var id = taskList[index].id;

                // 
                
                if(GlobalConfigs.submitDirectNfc){
                  _submitPatrolByNfc(str);
                }else{
                  Go().push(PatrolDetailPage(str,));
                }
              }

            }
            // showToast(ndef.cachedMessage.records[0].);
            NfcManager.instance.stopSession();
          },
          onError: (error) async{
          },
          // pollingOptions: {NfcPollingOption.iso14443, NfcPollingOption.iso15693},
          alertMessage: "准备扫描，将标签贴近手机"
      );
    }else{
      showToast("当前机型不支持nfc");
    }
  }

  @override
  void onCreated() {
    super.onCreated();
    getPatrolAreaList();
    getPatrolData();

  }

  @override
  void receiveMessage(SendMessageEvent event) {
    super.receiveMessage(event);
    if (event.msgCode == MessageConfig.REFRESH_PATROL) {
      getPatrolData();
    }
    if(event.msgCode==MessageConfig.NFC_READ_MESSAGE){
      // var index = controller.index;
      // 
      if(GlobalConfigs.submitDirectNfc){
        _submitPatrolByNfc(event.obj);
      }else{
        Go().push(PatrolDetailPage(event.obj, ));
      }
    }
  }

  void selectArea(){
    DataPickerView(context,areaList,onSubmitListener: (p1,p2,p3){
      var item = areaList[p1];
      selectedArea = item;
      notifyListeners();
      getPatrolData();
    }).show();
  }

  Future<void> _submitPatrolByNfc(String code) async {
    showLoadingDialog(msg: "正在提交...");
    try{
      await patrolModel.submitPatrolDirect(code);
      hideDialog();
      showToast("打卡成功");
      getPatrolData();
    }catch(e){
      showToast(NetErrorUtils.getNetError(e));
      hideDialog();
    }
  }
}
